﻿/*
 * Twipler - Twitter Web Client with features.
 *  
 *  Copyright (C) 2009, 2010. Ian Quigley
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details. 
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Twipler.App.Machine
{
    public class Environment
    {
        public List<string> Errors = new List<string>();

        internal Stack<object> Stack;
        internal int Index;

        private Dictionary<string, object> _variables = new Dictionary<string, object>();
                
        public object Execute(List<Instruction> program)
        {
			try
			{
				Stack = new Stack<object>();
				Errors = new List<string>();

				Index = 0;

				while ((Index < program.Count()) && (Errors.Count == 0))
				{
					program[Index].Exec(this);
					Index++;
				}

				if (Stack.Count() == 0)
					return null;

				return Stack.Pop();
			}
			catch (Exception ex)
			{
				throw new Exception("An exception occured while executing: "  + ProgramToString(program), ex);
			}
        }

		public static string ProgramToString(List<Instruction> program)
		{
			StringBuilder code = new StringBuilder();
			program.ForEach(inst => code.AppendFormat("{0} ", inst.ToString()));
			return code.ToString();
		}

    	internal object Variables_Descope(string name)
        {
            return Variables_Contains(name) ? _variables[name] : new VariableNotDefined();
        }

		internal bool Variables_Contains(string name)
		{
			return _variables.ContainsKey(name);
		}

        internal void Variables_Restore(string name, object obj)
        {
            if (obj is VariableNotDefined)
                return;

            _variables[name] = obj;
        }

		internal void Variables_Add(string name, object variable)
		{
			if (Variables_Contains(name))
				_variables[name] = variable;
			else
				_variables.Add(name, variable);
		}

		public object Variables_Get(string name)
		{
			if (Variables_Contains(name))
				return _variables[name];

			throw new Exception("Variable '{0}' is not declared.");
		}

		public void Variables_Set(string key, object val)
		{
			_variables[key] = val;
		}

        private class VariableNotDefined
        { }
    }
}